package com.rainszj.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * druid 数据源的相关配置
 */
@Configuration
public class DruidConfig {

    /**
     * 将 Druid数据源添加到Spring容器中，并绑定配置文件中设置的属性
     *
     * @return
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    /**
     * 配置 Druid 监控管理后台的Servlet；
     * 内置 Servlet 容器时没有web.xml文件，所以使用 SpringBoot的注册 Servlet 方式
     */
    @Bean
    public ServletRegistrationBean StatViewServlet() {

        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        Map<String, String> initParameters = new HashMap<String, String>();
        initParameters.put("loginUsername", "root");
        initParameters.put("loginPassword", "123456");
        // 允许哪些IP地址访问，为空代表谁都可以访问
        initParameters.put("allow", "127.0.0.1");

        bean.setInitParameters(initParameters);
        return bean;
    }

    /**
     * 配置 Druid 监控 之  web 监控的 filter
     * WebStatFilter：用于配置Web和Druid数据源之间的管理关联监控统计
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {

        FilterRegistrationBean bean = new FilterRegistrationBean(new WebStatFilter());

        // 过滤的路径
        bean.addUrlPatterns("/*");

        Map<String, String> initParameters = new HashMap<String, String>();

        // 排除哪些不过滤
        initParameters.put("exclusions", "*.js, *.css, *.ico, *.gif, *.png, *.jpg, /druid/*");

        bean.setInitParameters(initParameters);

        return bean;
    }


}
